package by.grsu.kononovich.dao.impl;

import java.io.Serializable;
import java.util.List;

import by.grsu.kononovich.entity.DamageInfo;
import by.grsu.kononovich.table.DamageInfoTable;

import com.epam.grsulab.webapi.dao.AbstractDao;

public class DamageInfoDao extends AbstractDao<DamageInfoTable, DamageInfo>{

	public DamageInfoDao(String rootFolderPath) {
		super(rootFolderPath);
	}

	@Override
	public void saveNew(DamageInfo newDmgInf) {
		newDmgInf.setId(getNextId());
		final DamageInfoTable damageInfoTable = deserializeFromXml();
		damageInfoTable.getRows().add(newDmgInf);
		serializeToXml(damageInfoTable);
	}

	@Override
	public void update(DamageInfo entity) {
		final DamageInfoTable damageInfoTable = deserializeFromXml();
		for (final DamageInfo row : damageInfoTable.getRows()){
			if(row.getId().equals(entity.getId())){
				row.setDamage(entity.getDamage());
				row.setDamagecost(entity.getDamagecost());
				row.setRefusal(entity.getRefusal());
				row.setReason(entity.getReason());
				break;
			}
		}
		serializeToXml(damageInfoTable);
	}

	@Override
	public DamageInfo get(Serializable id) {
		final DamageInfoTable damageInfoTable = deserializeFromXml();
		for (final DamageInfo row : damageInfoTable.getRows()){
			if (row.getId().equals(id)){
				return row;
			}
		}
		return null;
	}

	@Override
	public List<DamageInfo> getAll() {
		final DamageInfoTable damageInfoTable = deserializeFromXml();
		return damageInfoTable.getRows();
	}

	@Override
	public void delete(Serializable id) {
		final DamageInfoTable damageInfoTable = deserializeFromXml();
		DamageInfo toBeDeleted = null;
		for(final DamageInfo row : damageInfoTable.getRows()){
			if (row.getId().equals(id)){
				toBeDeleted = row;
				break;
			}
		}
		damageInfoTable.getRows().remove(toBeDeleted);
		serializeToXml(damageInfoTable);
	}

	@Override
	protected Class<DamageInfoTable> getTableClass() {
		return DamageInfoTable.class;
	}

}

